#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : color_capture.py
# @Author: DuJiabao
# @Date  : 2020/11/7
# @Desc  : 色彩捕捉

import cv2
import numpy as np


def extrace_object():
    capture = cv2.VideoCapture(1)
    while True:
        ret, frame = capture.read()  # frame是每一帧图像，ret是返回值，为0是表示图像读取完毕
        if not ret:
            break
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)  # 转换成HSV格式
        lower_hsv = np.array([0, 0, 221])  # 最低阈值
        upper_hsv = np.array([180, 30, 255])  # 最高阈值
        mask = cv2.inRange(hsv, lower_hsv, upper_hsv)  # 按照范围，取出二值化图像
        contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)  # 取出二值图像的所有轮廓
        if len(contours) != 0:
            areas = [cv2.contourArea(contour) for contour in contours]  # 计算所有轮廓的面积
            index = areas.index(max(areas))  # 寻找最大面积的轮廓的下标值
            point_contours = contours[index]  # 取出最大面积的轮廓
            frame = cv2.drawContours(frame, contours, index, (0, 0, 255), 2)  # 画出轮廓
            center, _, _ = cv2.minAreaRect(point_contours)  # 找出最小外接矩形的中心点
            # center = tuple([int(i) for i in center])  # 转换成元组形式
            cv2.circle(frame, (int(center[0]), int(center[1])), 3, (0, 0, 255), -1)  # 画出中心点
        cv2.imshow("video", frame)
        cv2.imshow("mask", mask)
        c = cv2.waitKey(1)
        if c == 27:  # 按Esc退出
            break


if __name__ == '__main__':
    extrace_object()
